<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>37.表单验证组件的代理工厂</title>
  <style>
    body {
      padding: 50px;
      background: #34495e;
    }

    input {
      border: solid 10px #ddd;
      height: 30px;
    }

    .error {
      border: solid 10px red;
    }
  </style>
</head>

<body>
  <input type="text" validate rule="max:12,min:3" />
  <input type="text" validate rule="max:3,isNumber" />
  <script>
    "use strict";
    //验证处理类
    class Validate {
      max (value, len) {
        return value.length <= len;
      }
      min (value, len) {
        return value.length >= len;
      }
      isNumber (value) {
        return /^\d+$/.test(value);
      }
    }

    //代理工厂
    function ProxyFactory (target) {
      return new Proxy(target, {
        get (target,key) {
          return target[key];
        },
        set (target,key, value) {
          console.log(key);
          return true;// 严格模式下，代理的set 必须返回boolean值
        }
      });
    }
    // 有validate 属性的表单菜需要验证
    const proxy = ProxyFactory(document.querySelectorAll('[validate]'));
    proxy.forEach( (item,i) => {
      item.addEventListener("keyup", function() {
        // 触发set
        proxy[i] = this;
      });
    });
    
  </script>
</body>

</html>